<template>
  <div class="edit_account">
    <!-- 页面主体 -->
    <v-main>
      <div class="page_name">
        <span class="title">编辑账号</span>
      </div>
      <div class="account_form">
        <el-form :model="editForm" :rules="rules" size="mini" ref="editForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="员工姓名" prop="staff_name" class="form_width">
            <el-input v-model="editForm.staff_name" :clearable="true" placeholder="请输入员工姓名"></el-input>
          </el-form-item>
          <el-form-item label="联系方式" prop="phone" class="form_width">
            <el-input v-model="editForm.phone" :clearable="true" placeholder="请输入联系方式"></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="role_ids">
            <el-select v-model="editForm.role_ids_change" @change="selectRole" placeholder="请选择角色">
              <el-option v-for="(item, index) in roleList" :label="item.display_name" :value="item.id" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="权限" prop="rights">
            <div class="form_wrapper">
              <el-tree :data="roleRights" :default-expand-all="true"></el-tree>
            </div>
          </el-form-item>
          <el-form-item label="门店权限" prop="shop_ids">
            <div class="form_wrapper">
              <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">门店列表</el-checkbox>
              <div style="margin: 15px 0;"></div>
              <el-checkbox-group v-model="checkedShops" @change="handleCheckedCitiesChange">
                <el-checkbox :checked="item.checked" :disabled="item.disabled" v-for="item in authCheckboxs" :label="item.id" :key="item.id">{{item.name}}</el-checkbox>
              </el-checkbox-group>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button  class="save_btn" @click="onSave" :loading="editLoading">保存</el-button>
            <el-button @click="navToAccount">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </v-main>
  </div>
</template>
<script type="text/ecmascript-6">
import { mapGetters } from 'vuex'
// components
import MainComp from '@/components/main'

// element-ui
import { Row, Col, Tabs, TabPane, Button, Tree, Input, Form, FormItem, Select, Option, Message, Checkbox, CheckboxGroup } from 'element-ui'
// API
import { APICheckAccount, APIEditAccount, APICanCreateRole } from '@/api/settings.js'
import permissionTree from '../permissionTree'

// 表单验证正则
const validateTel = (rule, value, callback) => {
  if (!value) {
    callback(new Error('联系方式不能为空'))
  } else if (/(\D)/g.test(value) || value.length > 15) {
    callback(new Error('联系方式格式不正确'))
  } else {
    callback()
  }
}

const validateStaffName = (rule, value, callback) => {
  if (!value) {
    callback(new Error('姓名不能为空'))
  } else if (value.length < 2 || value.length > 8) {
    callback(new Error('姓名长度须在2-8个字符'))
  } else {
    callback()
  }
}

export default {
  name: 'CreateAccount',

  components: {
    // elementUI component
    elRow: Row,
    elCol: Col,
    elButton: Button,
    elTabs: Tabs,
    elTabPane: TabPane,
    elTree: Tree,
    elInput: Input,
    elFormItem: FormItem,
    elForm: Form,
    elSelect: Select,
    elOption: Option,
    elCheckbox: Checkbox,
    elCheckboxGroup: CheckboxGroup,
    // 项目自定义组件
    vMain: MainComp
  },

  created () {
    // init request
    this.userid = this.$route.query.userid
    this.tabName = this.$route.query.tabName
    this.APICheckAccount(this.userid)
    this.APICanCreateRole()
  },

  data () {
    const validateShopIds = (rule, value, callback) => {
      if (this.checkedShops.length === 0) {
        callback(new Error('至少选择一家门店绑定'))
      } else {
        callback()
      }
    }
    return {
      authCheckboxs: [],
      rest: [],
      checkAll: null,
      isIndeterminate: false,
      checkedShops: [],
      tabName: null,
      currentUsershop: [],
      userid: null,
      editLoading: false,
      shopNames: [],
      editForm: {
        phone: '',
        staff_name: '',
        role_ids: null,
        role_ids_change: null,
        shop_ids: null,
        shop_ids_change: null
      },
      rules: {
        phone: [
          { required: true, validator: validateTel, trigger: 'blur' }
        ],
        staff_name: [
          { required: true, validator: validateStaffName, trigger: 'blur' }
        ],
        role_ids: [
          { required: true }
        ],
        shop_ids: [
          { required: true, validator: validateShopIds, trigger: 'change' }
        ]
      },
      roleList: []
    }
  },

  computed: {
    ...mapGetters([
      'mallId',
      'token',
      'mallinfo',
      'userinfo'
    ]),
    roleRights () {
      let currentRole = this.roleList.filter((item) => item.id === this.editForm.role_ids_change)
      let currentRoleIds = currentRole && currentRole[0] ? currentRole[0]['rank'] : null
      if (currentRoleIds !== null && currentRoleIds !== undefined) {
        return permissionTree[currentRoleIds]['rights']
      } else {
        return []
      }
    },
    shopList () {
      return this.mallinfo.shopNameList
    }
  },

  methods: {
    handleCheckAllChange (val) {
      let totalArr = [...this.shopList, ...this.rest].map(item => item.id)
      this.checkedShops = val ? totalArr : this.rest.map(item => item.id)
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange (value) {
      let totalLength = [...this.shopList, ...this.rest].length
      let checkedCount = value.length
      this.checkAll = checkedCount === totalLength
      this.isIndeterminate = checkedCount > 0 && checkedCount < totalLength
    },
    navToAccount () {
      this.$router.push({
        name: 'Settings',
        query: {
          tabName: this.tabName
        }
      })
    },
    onSave () {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          this.editLoading = true
          this.editForm.role_ids = [this.editForm.role_ids_change]
          this.editForm.shop_ids = this.checkedShops
          APIEditAccount({ userid: this.userid, formdata: this.editForm }).then((res) => {
            this.editLoading = false
            Message({
              message: '编辑成功',
              type: 'success'
            })
            this.$router.push({
              name: 'Settings',
              query: {
                tabName: this.tabName
              }
            })
            // this.$refs['addForm'].resetFields()
          }).catch(() => {
            this.editLoading = false
          })
        } else {
          return false
        }
      })
    },
    selectRole (value) {
      this.editForm.role_ids = value
      this.editForm.role_ids_change = value
    },
    selectShop () {
    },
    // ======= API ==================
    APICheckAccount (userid) {
      APICheckAccount({ userid })
        .then((res) => {
          // console.log('res:', res)
          this.editForm.staff_name = res.data.user.staff_name ? res.data.user.staff_name : ''
          this.editForm.phone = res.data.user.phone ? res.data.user.phone : ''
          this.editForm.role_ids = res.data.user.role_names ? res.data.user.role_names[0]['id'] : ''
          this.editForm.role_ids_change = res.data.user.role_names ? res.data.user.role_names[0]['id'] : ''
          this.currentUsershop = res.data.user.shop_names && res.data.user.shop_names.length > 0 ? res.data.user.shop_names : []
        })
        .then(() => {
          let users = [...this.currentUsershop]
          let editors = [...this.mallinfo.shopNameList]
          let rest = []
          for (let i = editors.length - 1; i >= 0; i--) {
            editors[i].disabled = false
            editors[i].checked = false
            for (let j = users.length - 1; j >= 0; j--) {
              if (users[j]['id'] === editors[i]['id']) {
                editors[i].checked = !editors[i].checked
                break
              }
            }
          }
          for (let i = users.length - 1; i >= 0; i--) {
            let same = false
            for (let j = editors.length - 1; j >= 0; j--) {
              if (users[i]['id'] === editors[j]['id']) {
                same = true
                break
              }
            }
            if (!same) {
              users[i]['disabled'] = true
              users[i]['checked'] = true
              editors.push(users[i])
              rest.push(users[i])
            }
          }
          return { editors, rest }
        })
        .then((res) => {
          this.authCheckboxs = res.editors
          this.rest = res.rest
          let totalShopList = [...this.authCheckboxs, ...this.rest]
          this.checkAll = !(totalShopList.some((item) => item.checked === false))
        })
    },
    APICanCreateRole () {
      APICanCreateRole()
        .then((res) => {
          this.roleList = res.data.roles
        })
    }
  }
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
  // scoped
  .edit_account {
    width: 100%;
    height: auto;
    box-sizing: border-box;
    background-color: #FFF;
    padding: 20px;
    box-shadow: 0 2px 3px 0 rgba(0, 0, 0, .2);
    .page_name {
      margin-bottom: 20px;
      .title{
        font-weight: bold;
        font-size: 18px;
      }
    }
    .account_form {
      width: 1000px;
      .form_width {
        width: 400px;
      }
      .form_wrapper {
        border-radius: 4px;
        padding: 20px;
        border: 1px solid #dcdfe6;
      }
      .save_btn{
        background-color: #159bd5;
        color: #ffffff;
      }
    }
  }
</style>
